#include "map.hh"


Map* Map::pinstance_ = 0;// initialize pointer

Map*
Map::instance ()
{
  if (pinstance_ == 0)  // is it the first call?
  {
    pinstance_ = new Map (); // create sole instance
  }
  return pinstance_; // address of sole instance
}

Map::Map ()
{
  width_ = 0;
  height_ = 0;
}

Map::Map (int a, int b) :
  width_(a), height_(b)
{
  int	i = 0;
  int	j = 0;

  for (i = 0; i < b; ++i)
    for (j = 0; j < a; ++j)
      tab_.push_back (new Case ());
}

int
Map::get_w ()
{
  return width_;
}

int
Map::get_h ()
{
  return height_;
}
void
Map::set_wh (int w, int h)
{
  int	i = 0;
  int	j = 0;

  width_ = w;
  height_ = h;

  tab_.clear ();
  for (i = 0; i < w; ++i)
    for (j = 0; j < h; ++j)
      tab_.push_back (new Case ());
}

int
Map::get_seed ()
{
  return seed_;
}

void
Map::set_seed (int s)
{
  seed_ = s;
}

Case&
Map::get_case (int h, int w)
{
  return *tab_[h * width_ + w];
}

void
Map::add_ant (int posx, int posy, Ants* ant)
{
  if (tab_[posx + posy * width_]->is_empty ())
    {
      tab_[posx + posy * width_]->set_full ();
      tab_[posx + posy * width_]->set_ant (ant);
    }
  else
    throw MyErrors (1);
}

void
Map::add_obstacle (int posx, int posy)
{
  if (tab_[posx + posy * width_]->is_empty ())
    tab_[posx + posy * width_]->set_full ();
  else
    throw MyErrors (1);
}

void
Map::add_ressource (std::string name, int posx, int posy)
{
  if (tab_[posx + posy * width_]->is_empty ())
  {
    tab_[posx + posy * width_]->set_full ();
    tab_[posx + posy * width_]->set_food (seed_);
    tab_[posx + posy * width_]->set_food_type (name);
  }
  else
    throw MyErrors (1);
}

static std::string
stringify (int x)
{
  std::ostringstream o;

  o << x;
  return o.str ();
}

static
std::string
print_num (int n)
{
  std::string s;
  s = stringify (n);

  if (n > 10)
    s = s.substr (s.size () - 1);
  return s;
}

void
Map::print_ant (int posx, int posy)
{
  std::string s ("  ");
  Case c;

  c = get_case (posy, posx);
  if (!c.is_empty ())
    {
      if (c.is_ant ())
      {
	c.get_ant ().print ();
	std::cout << print_num(c.get_ant ().get_team ());
      }
      else if (c.get_food () > 0)
	std::cout << "F ";
      else
	std::cout << "X ";
    }
  else
    std::cout << s;
}

std::vector<Case*>
Map::get_tab ()
{
  return tab_;
}
